<?php
namespace app\admin\model;
use think\Model;
class Cate extends Model
{
    //无线级分类
    public function getTreeRes(){
        # 查询数据
        $cateTreeRes = $this
            -> alias('t1')
            -> field('t1.* , t2.catename as pidname')
            -> join('bk_cate t2','t1.pid = t2.id','left') 
            -> order('sort desc') 
            -> select();
        # 将数据无线级排序
        return $this -> getTreeSort($cateTreeRes);
    }
    public function getTreeSort($res,$pid=0,$level=0){
        static $arr=[];
        foreach($res as $val){
            # 判断是否为顶级id或有顶级id
            if($val['pid'] == $pid){
                $val['level'] = $level;
                $arr[] = $val;
                $this -> getTreeSort($res,$val['id'],$level+1);
            }
        }
        return $arr;
    }
    
    //获取子极id
    public function getChildId($id){
        $cateres = $this -> select();
        $ids = $this -> _getChildIds($cateres,$id);
        $ids[] = (int)$id;
        $_ids = implode(',',$ids);
        return $_ids;
    }
    public function _getChildIds($res,$id){
        static $arr = [];
        foreach ($res as $key => $val) {
            # 判断是否有子极id
            if($val['pid'] == $id){
                $arr[] = $val['id'];
                $this -> _getChildIds($res,$val['id']);
            }
        }
        return $arr;
    }
}
